package com.chengqs.rainbow.im.gateway.util;

import cn.hutool.core.util.StrUtil;
import com.chengqs.rainbow.common.core.constant.SymbolConstants;
import com.chengqs.rainbow.common.core.exception.SystemException;
import com.chengqs.rainbow.common.im.constant.ZkConstants;
import com.chengqs.rainbow.common.im.util.ZkClient;
import com.chengqs.rainbow.im.gateway.constants.GatewayConstants;
import com.chengqs.rainbow.im.gateway.properties.ConfigProperties;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <B>主类名称：</B>GatewayContext<BR>
 * <B>概要说明：</B>enter<BR>
 *
 * @author: chengqs
 * @create: 2025-09-13 14:48:23
 **/
@Component
@RequiredArgsConstructor
public class GatewayContext {

    private final Timer timer = new Timer();

    private final AtomicInteger online = new AtomicInteger(0);

    private final AtomicInteger lastUpdateOnline = new AtomicInteger(0);

    private final ZkClient zkClient;

    @Value("${spring.profiles.active}")
    private String profile;

    private final ConfigProperties configProperties;

    /**
     * 定时任务，5秒后启动定时任务，每3秒执行一次
     */
    public void schedule() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (online.get() == lastUpdateOnline.get()) {
                    return;
                }
                try {
                    lastUpdateOnline.set(online.get());
                    zkClient.setData(getZkPath(), String.valueOf(online.get()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 5000, 3000);
    }

    public String getName() {
        return configProperties.getName();
    }

    @SneakyThrows
    public String ipAddress() {
        String ipAddress = System.getenv("im.ip-address");
        if (StrUtil.isBlank(ipAddress)) {
            ipAddress = configProperties.getIpAddress();
            if (StrUtil.isBlank(ipAddress)) {
                ipAddress = InetAddress.getLocalHost().getHostAddress();
            }
        }
        return ipAddress;
    }

    public Integer getPort() {
        return configProperties.getPort();
    }

    public boolean isTcp() {
        return GatewayConstants.PROTOCOL_TCP.equals(configProperties.getProtocol());
    }

    public boolean isWebSocket() {
        return GatewayConstants.PROTOCOL_WS.equals(configProperties.getProtocol());
    }

    public String getZkPath() {
        return getZkRootPath()
                + SymbolConstants.FORWARD_SLASH + getName()
                + SymbolConstants.COLON + ipAddress()
                + SymbolConstants.COLON + getPort();
    }

    public String getZkRootPath() {
        return ZkConstants.ZK_GATEWAY_PATH + SymbolConstants.FORWARD_SLASH + profile;
    }

    public String getZkRouteRootPath() {
        return ZkConstants.ZK_ROUTE_PATH + SymbolConstants.FORWARD_SLASH + profile;
    }

    public void online() {
        online.incrementAndGet();
    }

    public void offline() {
        online.decrementAndGet();
    }

    public int onlineCount() {
        return online.get();
    }
}
